const express = require("express");
const router = express.Router();
const { success, failure } = require("../../utils/responses");
const { User } = require("../../models");
const bcrypt = require('bcryptjs');
const jwt = require("jsonwebtoken");
const { NotFound, BadRequest, Unauthorized } = require("http-errors");
const { Op } = require("sequelize");

// qq邮箱相关包
const { createSixNum, QQsend } = require("../../utils/nodemailer");
const NodeCache = require("node-cache");
const myCache = new NodeCache();

// 时间戳转格式
function formatTimestamp(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/*
 **发送验证码（up这里是导出接口使用的，各位根据自己的代码做调整）
 **
 */
function request_Code(msg, res) {
  console.log("msg:", msg);
  console.log("res:", res);

  var datessss = new Date();
  console.log(
    "----------------------------------------------------------------------------------" +
      formatTimestamp(datessss) +
      "----------------------------------------------------------------------------------"
  );
  const email = msg.email;
  try {
    let code = createSixNum(); // 随机生成6位验证码

    // 将code存入缓存
    myCache.set("code", code, 300); // 缓存5分钟
    const domainPart = email.match(/(?<=@)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/);
    console.log("邮箱地址后缀：", domainPart[0]);
    if (domainPart[0] == "qq.com") {
      QQsend(email, code) //发送邮件的函数,传入邮箱和6位验证码
        .then((emailResult) => {
          console.log("邮件发送结果:", emailResult);
          res.json({
            status: true,
            code: 200,
            msg: "验证码发送成功",
            data: { email: email },
          });
        })
        .catch((err) => {
          console.error(err);
          res.json({
            code: 500,
            msg: "验证码发送失败，请稍后再试",
          });
        });
    } else {
      console.log("发送其他邮箱");
    }
  } catch (error) {
    console.log("尝试请求失败！", error);
  }
}

// 发送验证码接口
router.post("/send-code", (req, res) => {
  const { email } = req.body;
  console.log(req);

  // 基本验证
  if (!email) {
    return res.json({ msg: "请输入邮箱地址" });
  }

  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return res.json({ msg: "邮箱格式不正确" });
  }

  // 调用您现有的函数
  request_Code({ email: email }, res);
});

// 验证验证码接口
router.post("/verify-code", (req, res) => {
  const { code } = req.body;

  if (!code) {
    return res.json({
      msg: "请输入验证码",
      status: false,
      code: 400,
    });
  }

  // 从缓存中获取验证码
  const cachedCode = myCache.get("code");

  if (!cachedCode) {
    return res.json({
      msg: "验证码已过期或未发送，请重新获取",
      status: false,
      code: 400,
    });
  }

  if (code === cachedCode) {
    // 验证成功，删除缓存中的验证码
    myCache.del("code");
    return res.json({
      msg: "验证码验证成功",
      status: true,
      code: 200,
    });
  } else {
    return res.json({
      msg: "验证码错误，请重新输入",
      status: false,
      code: 400,
    });
  }
});

// 用户注册
router.post("/register", async (req, res) => {
  const { username, email, password, role } = req.body;
  try {
    const body = {
      username,
      email,
      password,
      role,
    };
    console.log("body", body);

    const user = await User.create(body);
    console.log("用户创建成功，开始处理响应...");
    delete user.dataValues.password; // 删除密码
    console.log(res);

    success(res, "创建用户成功。", { user }, 200);
  } catch (error) {
    failure(res, error);
  }
});

// 用户登录
router.post("/sign_in", async (req, res) => {
  try {
    const { username, password } = req.body;
    if (!username) {
      throw new BadRequest("邮箱/用户名必须填写。");
    }
    if (!password) {
      throw new BadRequest("密码必须填写。");
    }

    const condition = {
      where: {
        [Op.or]: [{ email: username }, { username: username }],
      },
    };
     // 通过email或username，查询用户是否存在
     const user = await User.findOne(condition);
     if (!user) {
       throw new NotFound('用户不存在，无法登录。');
     }
    // 验证密码
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      console.log(111);
      throw new Unauthorized("密码错误。");
    }

    // 生成身份验证令牌
    const token = jwt.sign(
      {
        userId: user.id,
      },
      process.env.SECRET,
      { expiresIn: "30d" }
    );
    success(res, "登录成功。", { token });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
